package com.kgc.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.kgc.api.goods.GoodsItemApi;
import com.kgc.api.user.FootPrintApi;
import com.kgc.bean.Footprint;
import com.kgc.bean.GoodsItem;
import com.kgc.bean.User;
import com.kgc.service.FootPrintService;
import com.kgc.util.RedisUtils;
import com.kgc.util.ResultBuildUtil;
import com.kgc.util.ReturnResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Classname FootPrintServiceImpl
 * @Description TODO
 * @Date 2021/6/21 10:11
 * @Created by 17402
 */
@Service
@Slf4j
public class FootPrintServiceImpl implements FootPrintService {

    @Autowired
    private RedisUtils redisUtils;
    @Reference(timeout = 30000)
    private FootPrintApi footPrintApi;
    @Reference(timeout = 30000)
    private GoodsItemApi goodsItemApi;
    @Override
    public ReturnResult<Map<String, Object>> addFootPrint2Cookie(String goodsId, HttpServletRequest req, HttpServletResponse resp) {
        //判断商品是否存在
        if(goodsItemApi.returnProductInformationAccordingToProductId(goodsId)==null){
            return ResultBuildUtil.fail("9003","该商品不存在");
        }
        Map<String,Object> returnData=new HashMap<>();
        //未登录存在cookie中
        String producthistoryid="";
        String id=goodsId;
        //获取Cookie数据并遍历，看是否已经存在producthistoryid这个Cookie
        Cookie[] cookies=req.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                String name=cookie.getName();
                String value=cookie.getValue();
                if(name.equals("producthistoryid")){
                    //存在producthistoryid这个cookie的话，就将它赋值给producthistoryid这个变量
                    producthistoryid=value;
                }
            }
        }

        //当遍历=之后发现没有这个Cookie是，就创建producthistoryid这个Cookie，并将商品id保存到其中
        if(producthistoryid==null||producthistoryid.equals("")){
            id+="#";
            System.out.println(id);
            Cookie producthistoryCookie=new Cookie("producthistoryid",id);
            resp.addCookie(producthistoryCookie);
        }else{
            //存在producthistoryid这个Cookie时，就将最近浏览的id添加到字符串的最前面
            //要保证最新浏览的商品id在最前面，有两种实现方式，当最下面哪种更简便
            //方式一：
//			String historyid="";
//			List<String> maskList=new ArrayList<String>();
//			String[] masks=producthistoryid.split(",");
//			for (String mask: masks){
//				if(!mask.equals(id)){
//					maskList.add(mask);
//				}
//			}
//         //ConvertUtil是将ArrayList里面的内容转换成字符串的一个帮助类
//			String rs=ConvertUtil.convertByMask(maskList, ",");
//			rs=id+","+rs;
            //或者这样实现，三行代码就可以搞定
            producthistoryid="#"+producthistoryid;
            producthistoryid=producthistoryid.replace("#"+id+"#", "#");
            String rs=id+producthistoryid;

            Cookie producthistoryCookie=new Cookie("producthistoryid",rs);
            resp.addCookie(producthistoryCookie);
        }
        returnData.put("msg","此次足迹已经保存！");
        return ResultBuildUtil.success(returnData);
    }

    @Override
    public ReturnResult<Map<String, Object>> addFootPrint2Database(String token, String goodsId) {
        if(redisUtils.get(token)==null){
            ResultBuildUtil.fail("9002","token错误，重新登录");
        }
        Map<String,Object> returnData=new HashMap<>();
        Integer userId= JSON.parseObject(redisUtils.get(token).toString(), User.class).getUserId();
        if(footPrintApi.findFootprint(goodsId,userId)!=null){
            Footprint footprint=footPrintApi.findFootprint(goodsId,userId);
            footprint.setFootprintTime(new Date());
            //足迹已经存在 去修改足迹的时间为最新时间
            footPrintApi.updateFootTime(footprint);
            returnData.put("msg","足迹已经存在 足迹时间已更新为最新时间");
        }else {
            //
            Footprint footprint=new Footprint();
            footprint.setFootprintGoodsId(goodsId);
            footprint.setUserId(userId);
            footprint.setFootprintTime(new Date());
            footPrintApi.addFootPrint(footprint);
            returnData.put("msg","此次浏览已经添加到我的足迹");
        }
        return ResultBuildUtil.success(returnData);
    }

    @Override
    public ReturnResult<Map<String, Object>> readFootPrintFromCookie(HttpServletRequest req) {
        Map<String,Object> returnData=new HashMap<>();
        String producthistoryid="";
        Cookie[] cookies=req.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                String name=cookie.getName();
                String value=cookie.getValue();
                if(name.equals("producthistoryid")){
                    //存在producthistoryid这个cookie的话，就将它赋值给producthistoryid这个变量
                    producthistoryid=value;
                }
            }
        }
        String[] goodsIdArray= producthistoryid.split("#");
        List<GoodsItem> goodsItemList=new ArrayList<>();
        for(int i=0;i<goodsIdArray.length;i++){
            System.out.println(goodsIdArray[i]);
            GoodsItem goodsItem=goodsItemApi.returnProductInformationAccordingToProductId(goodsIdArray[i]);
            if (null!=goodsItem) {
                goodsItemList.add(goodsItem);
            }
        }
        returnData.put("goodsItemList",goodsItemList);
        return ResultBuildUtil.success(returnData);
    }

    @Override
    public ReturnResult<Map<String, Object>> readFootPrintFromDatabase(User user) {
        Map<String,Object> returnData=new HashMap<>();
        List<Footprint> footprintList= footPrintApi.findFootprintByUserId(user.getUserId());
        //  returnData.put("data",footprintList);
        List<GoodsItem> goodsItemList=new ArrayList<>();
        if(null!=footprintList&&footprintList.size()>0){
            footprintList.forEach(footprint -> {
                GoodsItem goodsItem=goodsItemApi.returnProductInformationAccordingToProductId(footprint.getFootprintGoodsId());
                if(null!=goodsItem){
                    goodsItemList.add(goodsItem);
                }
            });
        }
        returnData.put("goodsItemList",goodsItemList);
        return ResultBuildUtil.success(returnData);
    }


    @Override
    public List<String> getGoodsIdFromCookies(HttpServletRequest req) {
        String producthistoryid="";
        Cookie[] cookies=req.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                String name=cookie.getName();
                String value=cookie.getValue();
                if(name.equals("producthistoryid")){
                    //存在producthistoryid这个cookie的话，就将它赋值给producthistoryid这个变量
                    producthistoryid=value;
                }
            }
        }
        String[] goodIdArray=producthistoryid.split("#");

        return Arrays.asList(goodIdArray);
    }

    @Override
    public void delGoodsIdFromCookies(HttpServletRequest req, HttpServletResponse resp) {
        Cookie[] cookies=req.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                String name=cookie.getName();
                String value=cookie.getValue();
                if(name.equals("producthistoryid")){
                    //存在producthistoryid这个cookie的话，就将它赋值给producthistoryid这个变量
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                }
            }
        }
    }
}
